<?php

/*
 * 本地店铺管理
 * 2016.10.19
 */

namespace Qwadmin\Controller;

use \Qwadmin\model;
class BizuserController  extends ComController{
	

	
	
    public function index()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('user');
        $pagesize = 10; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
		
		//显示权限
		$sh = isset($_REQUEST['outname']) ? $_REQUEST['outname'] : null;
		if(isset($sh))
		{
			
			$shc=array();
			$shc['outname']=array('like',"%".$sh."%");
			$shc['username']=array('like',"%".$sh."%");
			$shc['phone']=array('like',"%".$sh."%");
			//$shc['user_name']=array('like',"%".$sh."%");
			$shc['_logic'] = 'OR';
			$where[]=$shc;
		}
		if(session('uid')>5) $where[]=array('createuser'=>session('uid'));
		
        $count = $m->where($where)->count();
        $list = $m->where($where)->order('id desc')->limit($offset . ',' . $pagesize)->select();
        $tradeList=D("Trade")->getTradList();
        $statuslist=D('code')->getcode(25);
		
      
        $this->assign('tradeList',$tradeList);
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('sh', $sh);
        $this->assign('statuslist', $statuslist);
        $this->assign('page', $page);
        $this->display();
    }
    
     public function bookindex()  
    {   ///账务列表
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('user_book');
        $pagesize = 10; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
		if(session('uid')>5) $where[]=array('createuser'=>session('uid'));
		  
        $count = $m->where($where)->count();
        $list = $m->where($where)->limit($offset . ',' . $pagesize)->select();
        $tradeList=D("Trade")->getTradList();
		
		$xiaofeilist=D('code')->getcode(29);
        $userlist=D('user')->getUser();
        $statuslist=D('code')->getcode(37);


		//var_dump($statuslist);die();
        $this->assign('tradeList',$tradeList);
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('xiaofeilist', $xiaofeilist);
        $this->assign('userlist', $userlist);
        $this->assign('statuslist', $statuslist);
        $this->assign('page', $page);
        $this->display();
    }
    /*
  * 添加本地店铺
  * */
    public function add()
    {
        $tradeList = M('trade')->group('code')->select();
		$usertypelist=D('code')->getcode(1);
		$hezuotypelist=D('code')->getcode(4);
		$fromchannellist=D('code')->getcode(9);
		$requirementlist=D('code')->getcode(18);
		//var_dump($tradeList);
		//die();
		
        $this->assign('usertype',$usertypelist);
        $this->assign('hezuotype',$hezuotypelist);
        $this->assign('fromtype',$fromchannellist);
        $this->assign('requiretype',$requirementlist);
        $this->assign('tradeList',$tradeList);
		
        $this->display('form');
    }

	
	public function user()
	{
		///合作伙伴详情信息
		
		$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		if(!$id){
            $this->error('参数错误！');
            }
		$m = M('user');
        $currentuser = $m->where("id='$id'")->find();
		
		$p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('user_book');
        $pagesize = 100; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
		//if(session('uid')>5) $where[]=array('createuser'=>session('uid'));
		$where[] =array('user_id'=>$id);
        $count = $m->where($where)->count();
        $list = $m->where($where)->order('bind_id DESC,LEVEL DESC ,id DESC')->limit($offset . ',' . $pagesize)->select();
        $tradeList=D("Trade")->getTradList();
		
		$xiaofeilist=D('code')->getcode(29);
        $userlist=D('user')->getUser();
        $statuslist=D('code')->getcode(37);

		//var_dump($statuslist);die();
        $this->assign('tradeList',$tradeList);
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('xiaofeilist', $xiaofeilist);
        $this->assign('userlist', $userlist);
        $this->assign('statuslist', $statuslist);
        $this->assign('page', $page);
		
		$this->assign('currentuser',$currentuser);
		$this->display('user');
	}
	public function bookadd()
    {
		///id 参数为用户id，bind_id为入账id
        $ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
        $bind_id = isset($_REQUEST['bind_id']) ? $_REQUEST['bind_id'] : false;
		if(!$ids){
            $this->error('参数错误！');
            }
		$m = M('user');
        $currentuser = $m->where("id='$ids'")->find();

		//var_dump($currentuser);die();
		$tradeList = M('trade')->group('code')->select();
		$usertypelist=D('code')->getcode(1);
		$hezuotypelist=D('code')->getcode(4);
		$xiaofeitypelist=D('code')->getcode(29);
		$qudaotypelist=D('code')->getcode(33);
		$currentbook=array();
		if($bind_id)
		{
			unset($xiaofeitypelist['chanrge']);
			$currentbook['bind_id']=$bind_id;
		}else
		{
			unset($xiaofeitypelist['used']);
			unset($xiaofeitypelist['back']);
		};
	
        $this->assign('usertypelist',$usertypelist);
        $this->assign('xiaofeitype',$xiaofeitypelist);
        $this->assign('shoukuantype',$qudaotypelist);
        $this->assign('hezuotypelist',$hezuotypelist);
        $this->assign('currentbook',$currentbook);
        $this->assign('tradeList',$tradeList);
        $this->assign('currentuser',$currentuser);
		
        $this->display('book');
    }
	
	///订单绑定到商家
	public function  orderadddo()
	{
		//error_reporting(E_ALL);
		$userid = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		$bind_id = isset($_REQUEST['bind_id']) ? $_REQUEST['bind_id'] : false;
		$orderids = isset($_REQUEST['orderid']) ? $_REQUEST['orderid'] : false;
		
		if($bind_id==false) return false;
		//var_dump($orderids)
		if(!orderids) $this->error('error');
		 
		 $where = "ref in ("."'".implode("','",$orderids)."')";
	
		 $orders=M('order')->where($where)->select();
         $book=M('user_book');		
		 foreach($orders as $order)
		 {
			$wh=array('order_id'=>$order['ref']);
			$br=$book->where($wh)->find();
			if($br)
			{
				if(!$br['user_id'])
				{
					$br->data(array('user_id'=>$user_id))->save();///更新该订单到user_id
				}else
				{
					$error_str=$error_str." <li>".$order['ref']."已绑定其他用户。</li>";	
				}
				
			}else{
				///add order to book
                $book_arr=array();
                $book_arr['type']='used';
                $book_arr['order_id']=$order['ref'];
                $book_arr['user_id']=$userid;
                $book_arr['qudao']=$order['channel_code'];
                $book_arr['acount']=$order['amount_total'];
                $book_arr['creattime']=strtotime($order['date_order']);
                $book_arr['createuser']=session('uid');
                $book_arr['isvalid']=1;
                $book_arr['bind_id']=$bind_id;
                
					
				
				$book->add($book_arr);	
			
				}
			 
			 
		 }
		 
		 $this->success('绑定成功。'.$error_str);
		
	
	}
	public function orderadd()
	{  
		$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		$shkey = isset($_REQUEST['shkey']) ? $_REQUEST['shkey'] : false;
	    $bind_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		if($bind_id==false) return false;
		////page
		$p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('user');
        $pagesize = 60; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
		///

		if(isset($shkey))
		{
			$shc=array();
			$shc['ref']=array('like',"%".$shkey."%");
			$shc['buyer_name']=array('like',"%".$shkey."%");
			$shc['receive_info']=array('like',"%".$shkey."%");
			 
			$shc['_logic'] = 'OR';
			$where[]=$shc;
		}
		
		if(!$ids){
            $this->error('参数错误！');
            }
		$userbook=M('user_book')->where('user_id='.$ids)->select();
		
		$where[]=array("ref !=''");
		$m = M('user');
		$order=M('order')->where($where)->order('date_order desc')->limit($offset . ',' . $pagesize)->select();
		$count = M('order')->where($where)->count();
		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();

        $currentuser = $m->where("id='$ids'")->find();
		$this->assign('page', $page);
		$this->assign('currentuser',$currentuser);
		$this->assign('bind_id',$bind_id);
		$this->assign('orders',$order);
		$this->display('order');
	}
	
    /*
    * 删除用户 
    * */
    public function del()
    {

        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
        }elseif(!$ids){
            $this->error('参数错误！');
            }

        $map['id'] = array('in', $ids);
        if (M('user')->where($map)->delete()) {
            addlog('删除店铺ID：' . $ids);
            $this->success('恭喜，店铺删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }
  
        /*
    * 删除用户
    * */
    public function bookdel()
    {

        $ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
        if(!strpos(session('ugrand'),'salemanger'))
		{
			$this->error("权限不足",U('user',array('id'=>$user['user_id'])));
		}
        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
        }elseif(!$ids){
            $this->error('参数错误！'.$ids);
            }
        $map['id'] = array('in', $ids);
        if (M('user_book')->where($map)->delete()) {
            addlog('删除财务ID：' . $ids);
            $this->success('恭喜，删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }
    public function test()
	{
		echo "<pre>";
		

    $pfxpath="D:/bfkey.pfx";
    $cerpath="D:/pkkey.cer";
	$privkeypass="100018529_311044";
	$baofoo=new \Qwadmin\Model\BaofooApiModel($pfxpath,$cerpath,$privkeypass);
   
	
	
		$dataContent=array();
		$bizorder='o'.time().rand(1,1000);
		$dataContent['memberTransId']=$bizorder;
		$dataContent['goodsInfo']=array(array('goodsNum'=>'2','goodsName'=>"背包",'goodsPrice'=>'200'),array('goodsNum'=>'2','goodsName'=>"背包2",'goodsPrice'=>'200'));
		$dataContent['idCardNo']="431381198109106573";
		$dataContent['idName']="张三";
		$dataContent['mobile']="135162220098";
		$dataContent['bankCardNo']="6227000000110010010101";
		$dataContent['orderAmt']="800";
		$dataContent['transAmt']="800";
		$dataContent['orderCcy']="CCY";
		$dataContent['TransCcy']="CCY";
	
		
$response=$baofoo->requestorder($dataContent);  //返回
$bizorder=$response->memberTransId;


var_dump($response); 
  
  
   
     
		$dataContent=array();
	   	$dataContent['ccy']="CNY";
	
	   	$dataContent['memberApplyNo']=$bizorder; ///发起订单唯一编号
	   	$dataContent['memberTransDate']="20161214102140";
	   	$dataContent['memberTransId']=$bizorder;
	   	$dataContent['functionId']=300102;  ///海关编号
	   	$dataContent['companyOrderNo']=$bizorder;  ///订单编号
	   	$dataContent['remarks']="CNY";
	   	$dataContent['notifyUrl']="http://dc.shenghuigo.com/api.php?c=baofoo&a=recv";
	   	$dataContent['payFeeAmount']=0;
	   	$dataContent['payTaxAmount']=1.19;
	   	$dataContent['payGoodsAmount']=98;
	   	$dataContent['payPreAmount']=0.81;
	   	$dataContent['payTotalAmount']=800; 
		
		
      $response= $baofoo->cleargate($dataContent);
	  
	  var_dump($response);
	  
	  ///查询清关代码
      $dataContent=array();
	  $dataContent['memberApplyNo']=$bizorder;
	
      $response= $baofoo->querygate($dataContent);
	  
	  var_dump($response);
      
	}
	
       public function getBytes($string) {    
        $bytes = array();    
        for($i = 0; $i < strlen($string); $i++){    
           $bytes[] = ord($string[$i]);    
        }    
        return $bytes;    
       }    
	
	   public function post_json($url, $post_data = '', $timeout = 60){
        
		
		$poststr=http_build_query($post_data );
		
        $ch = curl_init($url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt( $ch, CURLOPT_POSTFIELDS,  $poststr);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        /*
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
            'Content-Type: application/json; charset=utf-8',  
            'Content-Length:' . strlen($poststr))  
        );  
        */
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  
        //curl_setopt($ch, CURLOPT_HEADER, false);
  
        $file_contents = curl_exec($ch);

      
  
        curl_close($ch);
        return $file_contents;
    }
	
 
    public function count()
	{  
		if(!session('uid')) $this->error('未登陆错误');
		$where[]=array('createuser'=>session('uid'));
		///总消费
		$userlist=M('user')->field('id')->where($where)->select();
		$useracount= M('user')->field("sum(acount) as acount,sum(acount_used) as used,sum(acount_remain) as remain")->where($where)->find();
		///今日消费信息
		
		$zt_time=strtotime(date('Y-m-d',strtotime('-1 day')));
		$jt_time=strtotime(date('Y-m-d',time()));
		$day_time=$jt_time-$zt_time;
		$mt_time=$jt_time+$day_time;
		
		echo "<pre>";
		///今日消费
		if(session('uid')>5) $wc[]=array('createuser'=>session('uid'));
		
		$all_acount=M('user_book')->field("sum(acount) as acount,user_id,type")->where($wc)->group('type')->select();
		var_dump($all_acount);
		
		$wc[]=array("creattime>$jt_time");
		$wc[]=array("creattime<$mt_time");
		$wc['_logic']='and';
		$zt_acount=M('user_book')->field("sum(acount) as acount,user_id,type")->where($wc)->group('type')->select();
		
		var_dump($zt_acount);
		 
		 echo $zt_time."<br/>".$jt_time."<br/>".$day_time;
		// M('user_book')->
		///最近一周的消费信息
		
		
		
		
		echo "tongji";
	}
  

    /*
    * 修改本地店铺
    * */  
    public function edit($id = 0)
    {
        $id = intval($id);
        $m = M('user');
        $currentmenu = $m->where("id='$id'")->find();
        if (!$currentmenu) {
            $this->error('参数错误！');
        }
	 
        $option = $m->select();
        $tradeList = M('trade')->group('code')->select();
		
		
		$usertypelist=D('code')->getcode(1);
		$hezuotypelist=D('code')->getcode(4);
		$fromchannellist=D('code')->getcode(9);
		$requirementlist=D('code')->getcode(18);
		//var_dump($tradeList);
		//die();
		
        $this->assign('usertype',$usertypelist);
        $this->assign('hezuotype',$hezuotypelist);
        $this->assign('fromtype',$fromchannellist);
        $this->assign('requiretype',$requirementlist);
		
        $this->assign('tradeList',$tradeList);
        $this->assign('option', $option);
        $this->assign('currentmenu', $currentmenu);
        $this->display('form');
    }

	public function bupdate()
	{
		///user_book
		$id = I('post.id', '', 'intval');
		$bind_id = I('post.bind_id', '', 'intval');
		$user_id = I('post.user_id', '', 'intval');
		$data=array();
		$data['type'] = I('post.usertype', '', 'strip_tags');
        $data['order_id'] = '';
        $data['user_id'] = I('post.user_id', '', 'intval');
        $data['qudao'] = I('post.shoukuan', '', 'strip_tags');
        $data['acount'] = I('post.account', '', 'strip_tags');
        $data['uppic'] = I('post.uppic', '', 'strip_tags');
        $data['creattime'] = time();
        $data['createuser'] =  session('uid');
        $data['bind_id'] = $bind_id;
        $data['isvalid'] = 0;
		if($data['type']=='chanrge')
		{
			$data['level'] = 1; ///1标识进入
		}else
		{
			$data['level'] = 0; ///0标识为出
		}
		
		 //var_dump($data);
        if ($id) {

            M('user_book')->data($data)->where("id='{$id}'")->save();
            addlog('编辑店铺，ID：' . $id);
        } else {
                // if(M('user')->where(array('outname'=> $data['outname']))->find()){
                //  $this->error('该合作伙伴已经存在！2'.$data['outname']);
                //}
                $addmodel=M('user_book');
				$addmodel->data($data)->add();
				
                addlog('新增合作伙伴，名称：' . $addmodel);
        }
        /*		
		///更新商家的金额
        $book= M('user_book')->field("sum(acount) as acount,type")->where('user_id='.$data['user_id'])->group('type')->select();
		$chanrge=0;$back=0;$used=0;
		foreach($book as $ac)
		{
			//var_dump($ac);
			if($ac['type']=='chanrge'&&isset($ac['type']))$chanrge=$ac['acount'];
			if($ac['type']=='back'&&isset($ac['type']))$back=$ac['acount'];
			if($ac['type']=='used'&&isset($ac['type']))$used=$ac['acount'];
			
		}
		$acount=$chanrge-$back;
		$remain=$acount-$used;
		
		$sql="update zt_user set acount=".$acount .",acount_used=".$used." ,acount_remain=".$remain. " where id=".$data['user_id'];
		
		M()->execute($sql);
        */
		$sql="update zt_user_book set bind_id=id where type='chanrge'";
		M()->execute($sql);
		$this->refreshacount($data['user_id']);
        $this->success('操作成功！',U('user',array('id'=>$data['user_id'])));
      
		
	}
	
	public function revist()
	{
		$p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = 10; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
		
		$count = M('user_revist')->where($where)->count();
		$page = new \Think\Page($count, $pagesize);
        $page = $page->show();
		
		
		 $list=M('user_revist')->where($where)->limit($offset,$pagesize)->select();
		 
		 $this->assign('list',$list);
		 $this->assign('page',$page);
		 $this->display('revist');
	}
	
	public function revistadd()
	{
		$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		if(!$id){
            $this->error('参数错误！');
            }
		$m = M('user');
        $currentuser = $m->where("id='$id'")->find();
		$revisttype=D('code')->getcode(40);
		$revistfor=D('code')->getcode(43);
		
		
		$this->assign('revistfor',$revistfor);
        $this->assign('revisttype', $revisttype);
        $this->assign('currentuser', $currentuser);
        $this->assign('currentmenu', $currentmenu);
		$this->display('revistadd');
	}
	
	public function revistadddo() ///add 执行
	{
		$user_id = I('post.user_id', '', 'intval');
		$data=array();
		$data['for'] = I('post.revistfor', '', 'strip_tags');
		$data['type'] = I('post.revisttype', '', 'strip_tags');
		$data['vistor'] = I('post.vistor', '', 'strip_tags');
		$data['logs'] = I('post.logs', '', 'strip_tags');
		$data['uppic'] = I('post.vistor', '', 'strip_tags');
		$data['user_id'] = $user_id;
		$data['createtime'] = time();
		
		M('user_revist')->add($data);
		
		
		$this->success('操作成功',U('Bizuser/user',array('id'=>$user_id)),true); 
	}
	
	public function refreshacount($user_id=0)
	{
		
		
		$data['user_id']=$user_id;	
		///更新商家的金额
        $book= M('user_book')->field("sum(acount) as acount,type")->where('user_id='.$data['user_id'])->group('type')->select();
		$chanrge=0;$back=0;$used=0;
		foreach($book as $ac)
		{
			//var_dump($ac);
			if($ac['type']=='chanrge'&&isset($ac['type']))$chanrge=$ac['acount'];
			if($ac['type']=='back'&&isset($ac['type']))$back=$ac['acount'];
			if($ac['type']=='used'&&isset($ac['type']))$used=$ac['acount'];
			
		}
		$acount=$chanrge-$back;
		$remain=$acount-$used;
		$sql="update zt_user set acount=".$acount .",acount_used=".$used." ,acount_remain=".$remain. " where id=".$data['user_id'];
		
		M()->execute($sql);

	}
	public function bcomfirm()
	{
		
		$id =isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		$data['isvalid'] = 1;
		if(!strpos(session('ugrand'),'salemanger'))
		{
			$this->error("权限不足",U('user',array('id'=>$user['user_id'])));
		}
		if($id)
		{
			M('user_book')->data($data)->where("id='{$id}'")->save();
			$user=M('user_book')->data($data)->find();
			$this->success('操作成功2！',U('user',array('id'=>$user['user_id'])));
		}else
		{
			$this->error('参数错误！',U('user',array('id'=>$user['user_id'])));
		}
		
	}
	
	public function bookrefresh()
	{
		
		$id =isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
		$this->refreshacount($id);
		$this->success('刷新成功',U('user',array('id'=>$id)));
		
		
	}
    public function update()
    {
		$id = I('post.id', '', 'intval');
        $data['outname'] = I('post.outname', '', 'strip_tags');
        $data['usertype'] = I('post.usertype');
        $data['address'] = I('post.address');
        $data['channel_code'] = I('post.channel_code');
        $data['trade_type'] = I('post.trade_type');
        $data['requirement'] = I('post.requirement');
		
        $m = M('user');
        $id = I('post.id', '', 'intval');
        $data['outname'] = I('post.outname', '', 'strip_tags');
        $data['usertype'] = I('post.usertype');
        $data['address'] = I('post.address');
        $data['channel_code'] = I('post.channel_code');
        $data['trade_type'] = I('post.trade_type');
        $data['requirement'] = I('post.requirement');
        $data['linkman'] = I('post.user_name');
        $data['phone'] = I('post.user_tel');
        $data['username'] = I('post.username');
        $data['passwd'] = I('post.password');
         
        $data['qqcode'] = I('post.qqcode');
        $data['demo'] = I('post.demo');
        $data['createtime'] = time();
        $data['createuser'] = session('uid');
        $data['status'] = I('post.status');
 
        $data['province'] = I('post.province');
        $data['city'] = I('post.city');
        $data['town'] = I('post.town');
    
	    //var_dump($data);
        if ($id) {
            if(M('user')->where(array('outname'=> $data['outname'],"id"=>array('neq',$id)))->find()){
                $this->error('该合作伙伴已经存在！');
            }
            M('user')->data($data)->where("id='{$id}'")->save();
            addlog('编辑店铺，ID：' . $id);
        } else {
                if(M('user')->where(array('outname'=> $data['outname']))->find()){
                  $this->error('该合作伙伴已经存在！2'.$data['outname']);
                }
                M('user')->data($data)->add();
                addlog('新增合作伙伴，名称：' . $data['name']);
        }

        $this->success('操作成功！',U('index'));
    }
}
